﻿using CommonServiceLocator;
using Prism.Interactivity.InteractionRequest;
using SPW.GenericDesktop.Views;
using SPW.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interactivity;

namespace SPW.GenericDesktop
{
    public class ModuleContainerPopupAction : TriggerAction<FrameworkElement>
    {
        protected override void Invoke(object parameter)
        {
            var arg = parameter as InteractionRequestedEventArgs;
            if (arg == null)
                return;

            var currentOwner = PlacementTarget ?? (Window)ServiceLocator.Current.GetInstance<IShell>();
            var windows = this.GetChildWindow(arg.Context);

            var callback = arg.Callback;
            EventHandler handler = null;
            handler =
                (o, e) =>
                {
                    windows.Closed -= handler;
                    callback();
                };
            windows.Closed += handler;
            windows.Owner = currentOwner;

            windows.Show();
        }

        #region 外部扩展属性
        public Window PlacementTarget
        {
            get { return (Window)GetValue(PlacementTargetProperty); }
            set { SetValue(PlacementTargetProperty, value); }
        }

        public static readonly DependencyProperty PlacementTargetProperty =
            DependencyProperty.Register("PlacementTarget", typeof(Window), typeof(ModuleContainerPopupAction), new PropertyMetadata(null));
        #endregion

        Window GetChildWindow(INotification notification)
        {
            var childWindow = this.CreateDefaultWindow(notification);
            //childWindow.DataContext = notification;

            return childWindow;
        }

        Window CreateDefaultWindow(INotification notification)
        {
            return (Window)new ModuleContainerPopup();
        }
    }
}
